package edu.ncc.airticket.web;

import edu.ncc.airticket.dao.MailServer;
import edu.ncc.airticket.model.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//import javax.mail.Message;
////import javax.mail.MessagingException;
////import javax.mail.Session;
////import javax.mail.Transport;
////import javax.mail.internet.InternetAddress;
////import javax.mail.internet.MimeMessage;
////import java.util.Properties;


import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * @author wangjie:
 * @version 创建时间：2019年8月27日 上午9:52:30
 * @Description 类描述:邮件发送的controller
 */

@RestController()
public class MailController {

    @Autowired
    private MailServer mailServer;

    /**
     * 简单邮件的发送
     * @return
     */
    @RequestMapping("/children/send")
    public String sendMail(@RequestBody Email email) throws MessagingException {
        mailServer.insert(email);
//        mailServer.sendMailServer("2251778131@qq.com", "你好", "明天去你家玩");
        String to = "2251778131@qq.com";
        // 发件人电子邮箱
        String from = "2251778131@qq.com";
        // 指定发送邮件的主机为 localhost
        String host = "localhost";
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties);
        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));
            // Set Subject: 头部头字段
//            message.setSubject("This is the Subject Line!");

            // 设置消息体
            message.setText("v=spf1 include:spf.mail.qq.com ~all");

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
        return "success";
    }


    /**
     * 发送带有附件的邮件
     */
//    @RequestMapping("/sendFile")
//    public String sendFileMail() {
//        File file=new File("C://Users//DELL//Desktop//学习资料.txt");
//        mailServer.sendFileMail("2631245486@qq.com", "你好dsf", "这是第二封带有附件的邮件", file);
//        return "success";
//    }
}

